<template>
  <div>
    <Button type="primary" v-if="access.includes('GAME_MANAGE')" class="back-button" @click="back()" icon="md-arrow-back">返回待审核列表</Button>
    <Button type="primary" v-else-if="access.includes('GAME_MANAGER')" class="back-button" @click="back()" icon="md-arrow-back">返回赛事列表</Button>
    <Card class="search-condition m-b-sm">
      <Row v-if="detail.eventsName" class="detail">
        <span>{{$config.userName(detail.eventsName,detail.eventsEnglishName)}}：</span>
        <Button @click="see" style="border: none;color: #359AFF;">查看基本信息</Button>
      </Row>
      <Row>
        <span>单场比赛名称：</span>
        <Input v-model="pageModel.fieldName" placeholder="请输入" clearable style="width: 150px" />
        <span>比赛阶段：</span>
        <InputNumber v-model="pageModel.fieldstartNumber" placeholder="请输入" clearable style="width: 100px" /><span style="margin:0;padding:0 10px">一</span>
        <InputNumber v-model="pageModel.fieldendNumber" placeholder="请输入" clearable style="width: 100px" />
        <span>比赛时间：</span>
        <DatePicker type="date" placeholder="请选择" style="width: 120px;margin-right:10px" v-model="pageModel.fieldstartTime"></DatePicker>
        <DatePicker type="date" placeholder="请选择" style="width: 120px;margin-right:10px" v-model="pageModel.fieldendTime"></DatePicker>
        <Button @click="fetchListStart" class="m-l-sm" type="primary" icon="md-search">筛选</Button>
        <Button @click="reset" class="m-l-sm" icon="md-sync">重置</Button>
      </Row>
    </Card>
    <Row class="m-b-sm" v-if="hasAccess">
      <Button type="primary" @click="dialog()" icon="md-add">添加比赛场次</Button>
      <Button type="primary" @click="downloadExcel">导入模板下载</Button>
      <upload-excel-button @upload="importExcel" type='primary' text="批量导入"></upload-excel-button>
      <!-- <Button
        type="primary"
        @click="exportExcel"
      >导出Excel</Button> -->

    </Row>
    <div v-if="initing">
      <Card>
        <Row>
          <Table :loading="loading" stripe border ref="selection" :columns="tableColumns" :data="tableData"></Table>
          <page-temp :total="total" :current="page.pageNo" :size="page.pageSize" @changePage='changePage'></page-temp>
        </Row>
      </Card>
      <Modal :styles="{top: '0px'}" v-model="visible" width='800' :mask-closable="false" :closable="false" title="编辑">
        <Card>
          <Row>
            <Col span="5">
            &nbsp;
            </Col>
            <Col span="14">
            <Form ref="model" :model="model" :rules="ruleInline" inline :label-width="100">
              <Row>
                <Col>
                <FormItem prop="fieldNumber" style="width:100%;" label="比赛场次">
                  <Input v-model="model.fieldNumber" placeholder="请输入" />
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="fieldName" style="width:100%;" label="单场比赛名称">
                  <Input v-model="model.fieldName" placeholder="请输入" />
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="fieldEnglishName" style="width:100%;" label="单场比赛名称（English）">
                  <Input v-model="model.fieldEnglishName" placeholder="请输入" />
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="gradeCode" style="width:100%;" label="比赛级别">
                  <dict code="ZGX_BSJB" model="model.gradeCode" :parentCode='detail.kindCode' :value="model.gradeCode" @click="getVal" style="width:100%;"></dict>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="eventsType" style="width:100%;" label="比赛类型">
                  <dict code="ZGX_BSLX" model="model.eventsType" :value="model.eventsType" @click="getVal" style="width:100%;"></dict>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="fieldTime" style="width:100%;" label="单场比赛日期">
                  <DatePicker type="date" :options="opFieldTime" placeholder="请选择" style="width:100%;" v-model="model.fieldTime"></DatePicker>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="fieldEndTime" style="width:100%;" label="比赛结束日期">
                  <DatePicker type="date" :options="opFieldTime2" placeholder="请选择" style="width:100%;" v-model="model.fieldEndTime"></DatePicker>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="operatingCompany" style="width:100%;" label="承办单位">
                  <Select v-model="model.operatingCompany" placeholder="请选择" clearable style="width: 100%;">
                    <Option v-for="(_item,index) in units" :key="index" :value="_item.teamId">{{_item.teamName}}</Option>
                  </Select>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="fieldAddressCountry" style="width:100%;" label="比赛地点-国家">
                  <dict model="model.fieldAddressCountry" :value="model.fieldAddressCountry" @getCode="getCode" @click="getVal" code="AG_OUT" style="width:100%;"></dict>
                </FormItem>
                <FormItem v-if="model.fieldAddressCountry==='A156'" label="比赛地点-省份" prop="fieldAddressProvince" style="width:100%;">
                  <dict model="model.fieldAddressProvince" :value="model.fieldAddressProvince" @getCode="getCode" @click="getVal" code="AG_IN" style="width:100%;"></dict>
                </FormItem>
                <FormItem v-if="model.fieldAddressCountry==='A156'" label="比赛地点-地市" prop="fieldAddressCity" style="width:100%;">
                  <dict model="model.fieldAddressCity" :value="model.fieldAddressCity" @click="getVal" @getCode="getCode" code="AG_IN" :parentCode='model.fieldAddressProvince' style="width:100%;"></dict>
                </FormItem>
                <FormItem v-if="model.fieldAddressCountry==='A156'" label="比赛地点-区县" prop="fieldAddressCounty" style="width:100%;">
                  <dict model="model.fieldAddressCounty" :value="model.fieldAddressCounty" @click="getVal" code="AG_IN" :parentCode='model.fieldAddressCity' style="width:100%;"></dict>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col v-if="model.fieldAddressCountry!=='A156'">
                <FormItem prop="address" style="width:100%;" label="比赛地点">
                  <Input v-model="model.address" placeholder="请输入" />
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Row>
                  <Col>
                  <FormItem prop="fieldCourt" style="width:100%;" label="比赛球场">
                    <Input v-model="model.fieldCourt" placeholder="请输入" />
                  </FormItem>
                  </Col>
                </Row>
              </Row>
            </Form>

            </Col>
          </Row>
          <!-- <spin-temp v-if="loading"></spin-temp> -->
        </Card>
        <div slot="footer">
          <Button @click="cancel">取消</Button>
          <Button @click="save" class="m-l-md" type="primary">确认</Button>
        </div>
      </Modal>
    </div>

  </div>
</template>

<script>
import dict from "_c/dict/dict.vue";
import dictSpan from "_c/dict/dict-span.vue";
import { getDict, check } from "@/api/configure";
import Api from "@/api/game-apply";
import uploadExcelButton from "_c/upload/upload-excel-button.vue";
const api = new Api();
// 赛事管理
export default {
  components: {
    dict,
    dictSpan,
    uploadExcelButton
  },
  data() {
    return {
      initing: false,
      loading: true,
      saving: false,
      total: 0,
      visible: false,
      delModal: false,
      hasAccess: false,
      AGOUTS: [],
      AGINS: [],
      units: [],
      gameApplyId: this.$route.params.id,
      detail: {
        applyId: this.$route.params.id
      },
      // 发布 取消发布
      selectedTableItems: [],
      pageModel: {
        fieldName: null,
        fieldTime: null,
        fieldstartNumber: null,
        fieldendNumber: null,
        fieldstartTime: null,
        fieldendTime: null
      },
      access: this.$store.state.user.access,
      opFieldTime: {
        disabledDate: date => {
          let self = this;
          // return (
          //   date &&
          //   !(
          //     date.valueOf() >= self.detail.startTime &&
          //     date.valueOf() <= self.detail.endTime
          //   )
          // );
          return (
            date &&
            !(
              date.valueOf() <= self.detail.endTime
            )
          );
        }
      },
      opFieldTime2: {
        disabledDate: date => {
          let self = this;
          return (
            date &&
            self.model.fieldTime &&
            !(
              date.valueOf() >= self.model.fieldTime &&
              date.valueOf() <= self.detail.endTime
            )
          );
        }
      },
      model: {},
      modelTemp: {
        eventsId: null,
        fieldAddressCountry: "A156"
      },
      page: {
        eventApplyId: this.$route.params.id,
        pageSize: this.$config.PAGE_SIZE,
        pageNo: 1
      },
      // 表单验证
      ruleInline: {
        fieldNumber: [
          { required: true, message: "请输入" },
          {
            pattern: this.$config.numReg,
            message: "请输入数字"
          },
          {
            max: this.$config.INPUT_NUMBER_SIZE,
            message: `数字最长为${this.$config.INPUT_NUMBER_SIZE}位`,
            transform(value) {
              return value == null ? "" : value.toString();
            }
          }
        ],
        fieldName: [
          { required: true, message: "请输入" },
          {
            max: this.$config.INPUT_ENGLISH_SIZE,
            message: `最多输入${this.$config.INPUT_ENGLISH_SIZE}个字符`
          }
        ],
        fieldEnglishName: [
          {
            max: this.$config.INPUT_ENGLISH_SIZE,
            message: `最多输入${this.$config.INPUT_ENGLISH_SIZE}个字符`
          }
        ],
        gradeCode: [{ required: true, message: "请选择" }],
        eventsType: [{ required: true, message: "请选择" }],
        fieldTime: [
          {
            required: true,
            type: "date",
            message: "请选择",
            trigger: "change"
          }
        ],
        fieldEndTime: [
          {
            required: true,
            type: "date",
            message: "请选择",
            trigger: "change"
          }
        ],
        operatingCompany: [{ required: false, message: "请选择" }],
        // 国家
        fieldAddressCountry: [{ required: false, message: "请选择" }],
        // 省份
        fieldAddressProvince: [{ required: false, message: "请选择" }],
        // 地市
        fieldAddressCity: [{ required: false, message: "请选择" }],
        // 县区
        fieldAddressCounty: [{ required: false, message: "请选择" }],
        address: [{ required: false, message: "请输入" }],
        fieldCourt: [
          // { required: true, message: "请输入" },
          {
            max: this.$config.INPUT_SIZE,
            message: `最多输入${this.$config.INPUT_SIZE}个字符`
          }
        ]
      },
      tableColumns: [
        {
          title: "比赛阶段",
          key: "fieldNumber",
          width: 100,
          align: "left",
          render: (h, params) => {
            let self = this;
            return h(
              "span",
              self.$config.fieldNumberStr(params.row.fieldNumber)
            );
          }
        },
        {
          title: "单场比赛名称",
          key: "fieldName",
          align: "left",
          ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = self.$config.userName(
              params.row.fieldName,
              params.row.fieldEnglishName
            );
            return h("span", { domProps: { title } }, title);
          }
        },
        {
          title: "比赛级别",
          key: "gradeCode",
          align: "left",
          width: 100,
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: "ZGX_BSJB",
                parentCode: this.detail.kindCode,
                value: params.row.gradeCode
              }
            });
          }
        },
        {
          title: "比赛类型",
          key: "eventsType",
          align: "left",
          width: 100,
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: "ZGX_BSLX",
                value: params.row.eventsType
              }
            });
          }
        },
        {
          title: "比赛日期",
          key: "fieldTime",
          align: "left",
          // ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = self.$config.getDate(
              params.row.fieldTime,
              params.row.fieldEndTime
            );
            return h("span", { domProps: { title } }, title);
          }
        },
        {
          title: "比赛地点",
          key: "fieldAddressCountry",
          align: "left",
          ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = self.$config.fieldAddress(
              params.row,
              self.AGOUTS,
              self.AGINS
            );
            return h("span", { domProps: { title } }, title);
          }
        },
        {
          title: "比赛球场名称",
          key: "fieldCourt",
          align: "left",
          ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = params.row.fieldCourt;
            return h("span", { domProps: { title } }, title);
          }
        },
        {
          title: "承办单位",
          key: "operatingCompany",
          align: "left",
          ellipsis: true,
          render: (h, params) => {
            let self = this;
            let row = self.units.find(
              x => x.teamId === params.row.operatingCompany
            ) || { teamName: params.row.operatingCompany };
            let title = row.teamName;
            return h("span", { domProps: { title } }, title);
          }
        },
        {
          title: "申请类型",
          key: "operationType",
          width: 90,
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: "ZGX_SSCZLX",
                value: params.row.operationType
              }
            });
          }
        },
        // {
        //   title: "发布状态",
        //   key: "state",
        //   align: "left",
        //   render: (h, params) => {
        //     return h(dictSpan, {
        //       style: { color: params.row.state === "0" ? "green" : "#CCCCCC" },
        //       props: { code: "ZGX_BSFB", value: params.row.state }
        //     });
        //   }
        // },
        {
          title: "操作",
          key: "action",
          align: "left",
          width: 200,
          render: (h, params) => {
            let self = this;
            if (!self.hasAccess) {
              return "";
            }
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px",
                    display: params.row.operationType !== "3" ? "" : "none"
                  },
                  on: {
                    click: () => {
                      self.dialog(params.row);
                    }
                  }
                },
                "修改"
              ),
              h(
                "Poptip",
                {
                  props: {
                    confirm: true,
                    title: "您确定要删除这条数据吗?",
                    transfer: true
                  },
                  on: {
                    "on-ok": () => {
                      //删除数据
                      this.del(params.row);
                    }
                  }
                },
                [
                  h(
                    "Button",
                    {
                      style: {
                        marginRight: "5px",
                        display: params.row.operationType !== "3" ? "" : "none"
                      },
                      props: {
                        size: "small",
                        type: "error",
                        placement: "top"
                      }
                    },
                    "删除"
                  )
                ]
              ),
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px",
                    display: ["1", "4"].includes(params.row.operationType)
                      ? "none"
                      : ""
                  },
                  on: {
                    click: () => {
                      self.restore(params.row, 4);
                    }
                  }
                },
                "撤销申请"
              )
            ]);
          }
        }
      ],
      tableData: []
    };
  },

  watch: {
    "model.fieldTime": function(newVal) {
      let self = this;
      // ||
      if (
        newVal != null &&
        (newVal.valueOf() > self.detail.endTime)
      ) {
        self.model.fieldTime = null;
      }
      if (
        self.model.fieldTime != null &&
        self.model.fieldEndTime != null &&
        self.model.fieldTime.valueOf() > self.model.fieldEndTime.valueOf()
      ) {
        self.model.fieldEndTime = null;
      }
    },
    "model.fieldEndTime": function(newVal) {
      let self = this;
      if (
        newVal != null &&
        self.model.fieldTime != null &&
        (newVal.valueOf() > self.detail.endTime ||
          newVal.valueOf() < self.model.fieldTime)
      ) {
        self.model.fieldEndTime = null;
      }
    }
  },

  mounted() {
    let self = this;
    Promise.all([
      getDict({ code: "AG_OUT" }),
      getDict({ code: "AG_IN" }),
      getDict({ code: "CBDW" }),
      api.getGameById(self.gameApplyId) // 获取赛事详情
    ])
      .then(data => {
        self.AGOUTS = data[0];
        self.AGINS = data[1];
        self.units = data[2];

        self.detail = {
          applyId: data[3].applyId,
          eventsId: data[3].eventsId,
          eventsName: data[3].eventsName,
          eventsEnglishName: data[3].eventsEnglishName,
          kindCode: data[3].kindCode,
          gradeCode: data[3].gradeCode,
          startTime: self.$moment(data[3].startTime).valueOf(),
          endTime: self.$moment(data[3].endTime).valueOf(),
          planField: data[3].planField,
          competitionState: data[3].competitionState
        };
        self.modelTemp.kindCode = data[3].kindCode;
        self.modelTemp.eventsId = data[3].eventsId;
        self.modelTemp.gradeCode = data[3].gradeCode;
        self.modelTemp.operatingCompany = data[3].undertakingUnit;
        self.modelTemp.eventApplyId = self.gameApplyId;
        self.page.eventsId = data[3].eventsId;
        if (data[3].verifyStatus === "3") {
          self.modelTemp.eventApplyId = null;
        }
        if (
          ["0", "3"].includes(data[3].verifyStatus) &&
          self.access.includes("GAME_MANAGER")
        ) {
          self.hasAccess = true;
        }
        self.initing = true;
        self.fetchListStart();
      })

      .catch(err => {
        self.initing = true;
        self.fetchListStart();
      });
  },
  methods: {
    back() {
      let path = "/game-management/";
      if (this.access.includes("GAME_MANAGE")) {
        path = "/game-verify-management/game-audit";
      } else {
        let { kindCode } = this.detail;
        switch (kindCode) {
          case "1":
            path += "career/man";
            break;
          case "2":
            path += "career/women";
            break;
          case "3":
            path += "amateur/man";
            break;
          case "4":
            path += "amateur/women";
            break;
          case "5":
            path += "teen/man-a";
            break;
          case "6":
            path += "teen/women-a";
            break;
          case "7":
            path += "teen/man-b";
            break;
          case "8":
            path += "teen/women-b";
            break;
          default:
            path += "career/man";
            break;
        }
      }
      this.$router.push({ path });
    },
    getCode(obj) {
      let self = this;
      if (obj.code === "AG_OUT") {
        if (obj.val !== "A156") {
          self.model.fieldAddressProvince = null;
          self.model.fieldAddressCounty = null;
          self.model.fieldAddressCity = null;
        }
      }
      self.$forceUpdate();
    },
    getData(obj) {
      let self = this;
      if (obj.code === "CBDW") {
        obj.units = obj.data;
      }
    },
    getVal(expression) {
      let self = this;
      eval(expression);
      self.$forceUpdate();
    },
    // 获取数据
    fetchListStart() {
      let self = this;
      self.page = { ...self.page, ...self.pageModel, pageNo: 1 };
      self.selectedTableItems = [];
      self.fetchList();
    },
    fetchList() {
      this.loading = true;
      api
        .queryMatchList(this.page)
        .then(data => {
          this.loading = false;
          this.tableData = data.list || [];
          this.total = data.count || 0;
        })
        .catch(error => {
          this.loading = false;
        });
    },
    // 分页
    changePage(pageNum) {
      this.page.pageNo = pageNum;
      this.fetchList();
    },
    // 重置
    reset() {
      let self = this;
      Object.keys(self.pageModel).forEach(x => {
        self.pageModel[x] = null;
      });
      this.fetchListStart();
    },
    // 保存
    save() {
      let self = this;
      this.$refs["model"].validate(valid => {
        if (valid) {
          self.saving = true;
          let model = {};
          Object.keys(self.model).forEach(x => {
            if (x.indexOf("_") !== 0) {
              model[x] = self.model[x];
            }
          });
          if (model.operationType == null) {
            model.operationType = "1";
          } else if (model.operationType === "4") {
            model.operationType = "2";
          }
          api
            .editMatch(model)
            .then(data => {
              self.saving = false;
              if (data) {
                self.cancel();
                self.fetchList();
              }
            })
            .catch(error => {
              self.saving = false;
            });
        }
      });
    },
    // 删除
    del(row) {
      let { applyId, operationType } = row;
      if (operationType === "1") {
        api.delMatch(applyId).then(data => {
          if (data) {
            this.fetchListStart();
          }
        });
      } else {
        this.restore(row, 3);
      }
    },
    // 撤销修改
    restore(row, newOperationType) {
      let { applyId, operationType } = row;
      api
        .restoreMatch({ applyId, operationType, newOperationType })
        .then(data => {
          if (data) {
            this.fetchListStart();
          }
        });
    },
    // 全选
    isSelected(_selected) {
      this.selectedTableItems = _selected;
    },
    // 发布 取消发布
    public(id, num) {
      let params = {
        fieldIdList: [],
        state: num
      };
      let self = this;
      if (!id) {
        if (this.selectedTableItems.length === 0) {
          this.$Message.warning("请至少选择一条");
          return;
        }
        params.fieldIdList = this.selectedTableItems.map(item => {
          return parseInt(item.fieldId);
        });
      } else {
        params.fieldIdList = [id];
      }

      api
        .matchpublic(params)
        .then(data => {
          self.loading = false;
          self.fetchListStart();
        })
        .catch(error => {
          self.selectedTableItems = [];
          self.loading = false;
        });
    },
    // 退出
    cancel() {
      let self = this;
      self.$refs["model"].resetFields();
      this.visible = false;
      this.loading = false;
    },
    see() {
      this.$router.push({
        path: "/game-apply-management/edit/" + this.detail.applyId
      });
    },
    //点击弹窗
    dialog(item) {
      let self = this;
      if (item) {
        self.model = { ...item };
        self.model.fieldTime = self.$moment(self.model.fieldTime).toDate();
        self.model.fieldEndTime =
          self.model.fieldEndTime != null
            ? self.$moment(self.model.fieldEndTime).toDate()
            : null;
      } else {
        if (self.detail.planField > self.total) {
          self.model = { ...self.modelTemp };
          self.model.fieldNumber = self.total + 1;
        } else {
          this.$Message.warning(
            `${self.detail.eventsName} 赛事设置计划场次为${
              self.detail.planField
            }场，已全部创建`
          );
          return;
        }
      }
      self.visible = true;
    },
    // // 导出excel
    // exportExcel() {
    //   let self = this;
    //   let params = self.page;
    //   api.ExportFieldExcel(params).then(fileUrl => {
    //     let link = document.createElement("a");
    //     link.href = fileUrl;
    //     let suffix = fileUrl.substr(fileUrl.lastIndexOf("."));
    //     link.download = self.detail.eventsName + "场次安排" + suffix;
    //     link.click();
    //   });
    // },
    // 批量导入
    importExcel(fileUrl) {
      let self = this;
      let params = {
        ftpFile: fileUrl,
        eventApplyId: self.detail.applyId,
        eventsId: self.detail.eventsId
      };
      api.importFieldExcel(params).then(data => {
        self.fetchListStart();
      });
    },
    downloadExcel() {
      let link = document.createElement("a");
      link.href = this.$config.fieldExcelTempUrl;
      link.download = "比赛场次批量导入模板.xlsx";
      link.click();
    }
  }
};
</script>

<style scoped>
.ivu-btn-primary {
  margin: 0 4px;
}
.ivu-card-bordered {
  border: 1px solid #fff;
}
.ivu-card:hover {
  box-shadow: none;
}
.demo-spin-col {
  border: none;
}
.ivu-input-number {
  width: 100%;
}
.detail .ivu-btn:focus {
  box-shadow: none;
}
</style>
